﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace DataAccessLayer.DAL
{
    public class SellerBidDAL
    {
        public static void AddBid(String username, SellerBid bid)
        {
            using (var context = new ReverseAuctionEntities())
            {
                User user = context.Users.SingleOrDefault(u => u.Username == username);
                user.SellerBids.Load();
                user.SellerBids.Add(bid);
                context.Users.ApplyCurrentValues(user);
                context.SaveChanges();
            }
        }
        
        public static Array GetBids(int auctionID)
        {
            using (var context = new ReverseAuctionEntities())
            {
                var result = from user in context.Users
                             from bid in context.SellerBids
                             where user.ID == bid.SellerID 
                             where bid.AuctionID==auctionID
                             orderby bid.BidDate descending
                             select new { Username = user.Username, BidValue = bid.BidValue, Description = bid.Description,
                                        bid.ID};
                return result.ToArray();
            }
        }

        public static Array GetBestCost(int auctionID)
        {
            using (var context = new ReverseAuctionEntities())
            {
                var result = (from user in context.Users
                              from bid in context.SellerBids
                              where user.ID == bid.SellerID
                              where bid.AuctionID == auctionID
                              orderby bid.BidValue
                              select new { Username = user.Username, BidValue = bid.BidValue, Description = bid.Description }).Take(10);
                return result.ToArray();
            }
        }

        public static SellerBid GetByID(int id)
        {
            using (var context = new ReverseAuctionEntities())
            {
                return context.SellerBids.SingleOrDefault(u => u.ID == id);
            }
        }
    }
}
